<template>
  <el-breadcrumb  style="font-size: 30px">
    订单列表
    <el-divider></el-divider>
  <p>
    <div style="padding-bottom: 50px">
    <el-button @click="searchByName()" type="primary" icon="el-icon-search" style="float:right;">搜索</el-button>
    <el-input placeholder="请输入姓名：" v-model="customer.name" prefix-icon="el-icon-search" style="width: 300px; padding-right: 10px;float: right" ></el-input>
    <el-input  placeholder="请输入电话号码：" v-model="customer.phoneNumber" prefix-icon="el-icon-search" style="width: 300px; padding-right: 10px;float: left" ></el-input>
    <el-button @click="searchByPhone()" type="primary" icon="el-icon-search" style="float:left;">搜索</el-button>
    </div>
    <div v-if="abled">
      <a href="javascript:void(0)" style=" font-size: 16px; float: right" @click="goBack()">返回</a>
    </div>
    <div v-else>
      <a @click="selectHistory()" href=" javascript:void(0)" style=" font-size: 16px; float: right">历史订单</a>
    </div>


  <el-table
      :data="orderArr"
      style="width: 100%">
    <el-table-column prop="orderNumber" label="订单编号" width="320"></el-table-column>
    <el-table-column prop="roomId" label="房间号" width="150"></el-table-column>
    <el-table-column prop="name" label="订房人" width="150"></el-table-column>
    <el-table-column prop="state" label="状态" width="150"></el-table-column>
    <el-table-column prop="gender" label="性别" width="100"></el-table-column>
    <el-table-column prop="phone" label="电话" width="150"></el-table-column>
    <el-table-column prop="price" label="价格" width="150"></el-table-column>
    <el-table-column prop="startTime" label="创建时间" width="200"></el-table-column>
    <el-table-column fixed="right" label="操作" width="200" align="center">
      <template slot-scope="scope">
        <el-button @click="openEditDialog(scope.row)"  icon="el-icon-edit" type="text" size="small">详情</el-button>
        <el-button @click="openDeleteConfirm(scope.row)" type="text" icon="el-icon-delete" size="small">删除</el-button>
        <div v-if="scope.row.state=='待入住'">
        <el-button @click="liveIn(scope.row)"  size="small" type="danger" icon="el-icon-check" >办理入住</el-button>
        </div>
        <div v-else-if="scope.row.state=='已入住'">
          <el-button size="small" type="success" icon="el-icon-check" @click="openSuccessConfirm(scope.row)" >点击完成</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>
    <!-- 以下是弹出的比对客户信息的对话框 -->
    <el-dialog  title="客户信息" :visible.sync="dialogForm">
      <el-form :model="form">
        <el-form-item label="订单人身份证" :label-width="formLabelWidth">
          <el-input v-model="form.cardNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="随从人身份证" :label-width="formLabelWidth">
          <el-input v-model="form.otherCardNumber" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="checkMessage()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 以下是弹出的修改订单的对话框 -->
    <el-dialog title="订单详情" :visible.sync="dialogFormVisible">
      <el-form :model="editForm">
        <el-form-item label="房间号" :label-width="formLabelWidth">
          <el-input v-model="editForm.roomId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="房间类型" :label-width="formLabelWidth">
          <el-input v-model="editForm.roomType" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="订单人姓名" :label-width="formLabelWidth">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="订单人性别" :label-width="formLabelWidth">
          <el-input v-model="editForm.gender" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="订单人电话" :label-width="formLabelWidth">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="订单人身份证" :label-width="formLabelWidth">
          <el-input v-model="editForm.cardNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="随从人姓名" :label-width="formLabelWidth">
          <el-input v-model="editForm.otherName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="随从人性别" :label-width="formLabelWidth">
          <el-input v-model="editForm.otherGender" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="随从人电话" :label-width="formLabelWidth">
          <el-input v-model="editForm.otherPhone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="随从人身份证" :label-width="formLabelWidth">
          <el-input v-model="editForm.otherCardNumber" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button :disabled="isabled" type="primary" @click="submitEditForm()">修 改</el-button>
      </div>
    </el-dialog>
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </el-breadcrumb>
</template>

<script>

export default {
  name: "OrderList",
  data() {
    return {
      order:{id:'',state:''},
      abled:false,
      isabled: false,
      customer:{name:"",phoneNumber:""},
      dialogFormVisible: false,
      dialogForm: false,
      selectByPhone:false,
      selectByName:false,
      form: {
        cardNumber: '',
        otherCardNumber:''
      },
      editForm: {
        id: '',
        roomId: '',
        roomType: '',
        name: '',
        gender: '',
        phone: '',
        cardNumber: '',
        otherName: '',
        otherGender: '',
        otherPhone: '',
        otherCardNumber: '',
        price:'',
        startTime:''
      },
      orderArr:[], //存放接收后端的数据
      page: 1, // 当前页 默认设值1
      pageSize: 10, // 每页显示条目 默认设置5
      total: 20 ,// 条目总数
      formLabelWidth: '180px'
    }
  },
  methods: {
    cancel(){
      this.dialogForm = false;
      this.loadPage(this.page,this.pageSize);
    },
    liveIn(order){
      this.dialogForm = true;
      order.state = 1;
      this.order.state = order.state;
      this.order.id = order.id;
    },
    openSuccessConfirm(order) {
      this.$confirm('请确保客户已退房，订单完成后无法改变', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.success(order);
      }).catch(() => {

      });
    },
    success(order) {
      order.state = 2;
      console.log(order.state)
      let url = 'http://localhost:9085/orders/' + order.id + '/updateInfoById';
      console.log(url)
      let formData = this.qs.stringify(order);
      console.log('formData = ' + formData);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: '订单完成！',
            type: 'success'
          });
          this.updateEnable({id:order.roomId,enable: 1});
            this.loadPage();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
              this.loadPage();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },

    checkMessage(){
      let url = 'http://localhost:9085/orders/getOrderByCardNumber'+ '?cardNumber='+this.form.cardNumber +'&otherCardNumber='+ this.form.otherCardNumber;
      console.log('url = ' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        console.log(responseBody);
        if (responseBody.state == 20000) {
          let url = 'http://localhost:9085/orders/' +this.order.id + '/updateInfoById';
          console.log(url)
          let formData = this.qs.stringify(this.order);
          console.log('formData = ' + formData);
          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.dialogForm = false;
              this.$message({
                message: '办理入住成功！',
                type: 'success'
              });
              this.loadPage();
            } else if (responseBody.state == 40400) {
              this.$alert(responseBody.message, '警告', {
                confirmButtonText: '确定',
                callback: action => {// eslint-disable-line no-unused-vars
                  this.loadPage();
                }
              });
            } else {
              this.$message.error(responseBody.message);
            }
          })
        }
      });
    },
    goBack(){
      this.abled=false;
      this.page=1;
      this.loadPage(this.page,this.pageSize);
    },
    selectHistory(page,pageSize){
      this.abled=true;
      let url = "http://localhost:9085/orders/History";
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url,{
            params:{
              page,
              pageSize
            }
          }).then(response => {
        let responseBody = response.data;
        let arr = responseBody.data.list;
        console.log(arr);
        for(var i=0; i < arr.length; i++) {
          if (arr[i].state == 2) {
            arr[i].state = '已完成'
          }
        }
        this.orderArr = arr;
        this.total = responseBody.data.total;
        console.log(responseBody);
      });
    },
    openEditDialog(order) {
      if(this.judge()){
        this.isabled = true;
      }
      let url = 'http://localhost:9085/orders/' + order.id;
      console.log('url = ' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.dialogFormVisible = true;
          this.editForm = responseBody.data;
        } else {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
              this.loadPage();
            }
          });
        }
      });
    },
    submitEditForm() {
      let url = 'http://localhost:9085/orders/' + this.editForm.id + '/updateInfoById';
      console.log('url = ' + url);
      let formData = this.qs.stringify(this.editForm);
      console.log('formData = ' + formData);

      this.axios.create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        let responseBody = response.data;
        console.log(responseBody);
        if (responseBody.state == 20000) {
          this.$message({
            message: '修改订单成功！',
            type: 'success'
          });
          this.loadPage();
          this.dialogFormVisible = false;
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
              this.dialogFormVisible = false;
              this.loadPage();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },
    openDeleteConfirm(order) {
      this.$confirm('是否删除名为【'+order.name+'】的订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(order);
      }).catch(() => {

      });
    },
    handleDelete(order) {
      let url = 'http://localhost:9085/orders/' +order.id + '/delete';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: '删除订单成功！',
            type: 'success'
          });
          this.updateEnable({id:order.roomId,enable: 1});
          if(this.judge()){
            this.selectHistory();
          }else{
            this.loadPage();
          }
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
              this.loadPage();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },
    searchByName(page, pageSize){
      this.selectByPhone = false;
      let url = "";
      if(this.orderArr[0].state =='已完成'){
        url = "http://localhost:9085/orders/selectHistoryByName"+"?name="+this.customer.name;
      }else {
        url = "http://localhost:9085/orders/selectByName"+"?name="+this.customer.name;
      }
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url,{
            params:{
              page,
              pageSize
            }
          }).then(response => {
        let responseBody = response.data;
        let arr = responseBody.data.list;
        console.log(arr);
        for(var i=0; i < arr.length; i++){
          if(arr[i].state == 0){
            arr[i].state = '待入住'
          }else if(arr[i].state == 1){
            arr[i].state = '已入住'
          }else if (arr[i].state == 2){
            arr[i].state = '已完成'
          }
        }
        console.log('state=' + responseBody.state);
        this.total = responseBody.data.total;
        this.orderArr = arr;
        this.selectByName = true;
        this.abled = true;
      });
    },
    searchByPhone(page, pageSize){
      let url = "";
      if(this.orderArr[0].state =='已完成'){
         url = "http://localhost:9085/orders/selectHistoryByPhone"+"?phone="+this.customer.phoneNumber;
      }else {
         url = "http://localhost:9085/orders/selectByPhone"+"?phone="+this.customer.phoneNumber;
      }
      console.log(this.orderArr[0]);
      console.log(url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url,{
            params:{
              page,
              pageSize
            }
          }).then(response => {
        let responseBody = response.data;
        let arr = responseBody.data.list;
        console.log(responseBody);
        for(var i=0; i < arr.length; i++){
          if(arr[i].state == 0){
            arr[i].state = '待入住'
          }else if(arr[i].state == 1){
            arr[i].state = '已入住'
          }else if (arr[i].state == 2){
            arr[i].state = '已完成'
          }
        }
        console.log('state=' + responseBody.state);
        this.total = responseBody.data.total;
        this.orderArr = arr;
        this.selectByPhone = true;
        this.abled = true;
      });
    },
    judge(){
        if(this.orderArr[0].state == '已完成'){
          return true;
        }
          return false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      if(this.selectByPhone){
        this.searchByPhone(this.page,this.pageSize)
      }else if(this.selectByName) {
        this.searchByName(this.page,this.pageSize)
      }else if(this.judge()) {
        this.selectHistory(this.page, this.pageSize)
        console.log(`当前页: ${val}`);
      }
      else {
        this.loadPage(this.page,this.pageSize);
        console.log(`当前页: ${val}`);
      }
    },
    handleCurrentChange(val) {
      this.page = val;
      if(this.selectByPhone){
        this.searchByPhone(this.page,this.pageSize)
      }else if(this.selectByName) {
      this.searchByName(this.page,this.pageSize)
      }else if(this.judge()) {
        this.selectHistory(this.page, this.pageSize)
        console.log(`当前页: ${val}`);
      }
      else {
        this.loadPage(this.page,this.pageSize);
        console.log(`当前页: ${val}`);
      }
    },
    loadPage(page,pageSize) {
      let url = "http://localhost:9085/orders";
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url,{
        params:{
          page,
          pageSize
        }
      }).then(response => {
        let responseBody = response.data;
        let arr = responseBody.data.list;
        console.log(arr);
        for(var i=0; i < arr.length; i++){
          if(arr[i].state == 0){
            arr[i].state = '待入住'

          }else if(arr[i].state == 1){
            arr[i].state = '已入住'
          }else if (arr[i].state == 2){
            arr[i].state = '已完成'
          }
        }
        this.orderArr = arr;
        this.total = responseBody.data.total;
        console.log(responseBody.data)

      });
    },
    updateEnable(room) {
      let enableStatus = [
        {'url': '/disable', text: '禁用'},
        {'url': '/enable', text: '启用'}
      ];
      let url = 'http://localhost:9085/rooms/'
          + room.id + enableStatus[room.enable].url;
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          console.log("启用房间成功")
          this.loadRoomList(this.page, this.pageSize);
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
              this.loadRoomList(this.page, this.pageSize);
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },

  },

  mounted() {
    this.loadPage(this.page,this.pageSize);
  }

}
</script>

<style scoped>
.block {
  text-align: center;
  margin-top: 10px;
}
</style>
